package com.common.utils.file;



import cn.hutool.core.io.file.FileReader;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import it.sauronsoftware.jave.*;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * @Author: zengliang
 * @Description: 音频文件工具类
 * @Date:Created in 12:04 2022/7/30
 * @Modified By:
 */
public class AudioUtil  extends Encoder{

    //重写方法
    protected void processErrorOutput(EncodingAttributes attributes, BufferedReader errorReader, File source, EncoderProgressListener listener)
            throws EncoderException, IOException {
        // 屏蔽默認的錯誤處理
        try {
            String line;
            while ((line = errorReader.readLine()) != null) {
                // logger.debug(line);
            }
        } catch (Exception exp) {
        }
    }

    /**
     * 任意音频转Mp3文件，执行转化过程
     * @param source      源文件
     * @param desFileName 目标文件名
     * @return 转化后的文件
     */
    public static File convertToMp3(File source, String desFileName) throws Exception {
        File target = new File(desFileName);
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libmp3lame");
        audio.setBitRate(new Integer(36000)); //音频比率 MP3默认是1280000
        audio.setChannels(new Integer(2));
        audio.setSamplingRate(new Integer(44100));
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        AudioUtil encoder = new AudioUtil();
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * 获取录音文件时长（秒）.MP3文件
     * @param file
     * @return
     */
    public static int getDuration(File file) {
        int length = 0;
        try {
            MP3File mp3File = (MP3File) AudioFileIO.read(file);
            MP3AudioHeader audioHeader = (MP3AudioHeader) mp3File.getAudioHeader();
            // 单位为秒
            length = audioHeader.getTrackLength();
            return length;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }

    /**
     * 文本 转语音 功能
     * @param text 文本
     * @param volume  音量
     * @param rate  朗读速度
     * @return
     */
    public static byte[] textToVoice(String text, Integer volume, Integer rate) {
        // 文字转语音
        ActiveXComponent ax = null;
        Dispatch spVoice = null;
        Dispatch spAudioFormat = null;
        Dispatch spFileStream = null;
        // 文件地址
        String fileUrl = "./";
        String fileName = "text" + "_" + Calendar.getInstance().getTimeInMillis();
        String fileExtension = ".mp3";
        String filePath = fileUrl + fileName + fileExtension;
        // 文件转流
        File file = null;
        try {
            ax = new ActiveXComponent("Sapi.SpVoice");
            spVoice = ax.getObject();
            // 构建文件流把生成语音文件
            ax = new ActiveXComponent("Sapi.SpFileStream");
            spFileStream = ax.getObject();

            ax = new ActiveXComponent("Sapi.SpAudioFormat");
            spAudioFormat = ax.getObject();

            // 设置音频流格式
            Dispatch.put(spAudioFormat, "Type", new Variant(22));
            // 设置文件输出流格式
            Dispatch.putRef(spFileStream, "Format", spAudioFormat);

            file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }

            // 调用输出 文件流打开方法，创建一个.mp3文件，创建前必须检查这个文件是否存在，否则创建会失败
            Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(3), new Variant(true));
            // 设置声音对象的音频输出流为输出文件对象
            Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
            // 设置音量 0到100
            Dispatch.put(spVoice, "Volume", new Variant(volume));
            // 设置朗读速度
            Dispatch.put(spVoice, "Rate", new Variant(rate));
            // 开始朗读
            Dispatch.call(spVoice, "Speak", new Variant(text));

            // 关闭输出文件
            Dispatch.call(spFileStream, "Close");
            Dispatch.putRef(spVoice, "AudioOutputStream", null);

            //return getBytesByFile(file);
            //返回一个byte[] 给前端调用
            return new FileReader(file).readBytes();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(file.exists()) {
                file.delete();
            }
            spAudioFormat.safeRelease();
            spFileStream.safeRelease();
            spVoice.safeRelease();
            ax.safeRelease();
        }
        return null;
    }

}
